package com.zjs.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjs.dao.BookDao;
import com.zjs.pojo.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
@EnableScheduling
public class BookTask {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private BookDao bookdao;

    boolean first = true;

    @Scheduled(fixedRate = 1000*60)
    public void createes(){
        if (!elasticsearchRestTemplate.indexOps(Book.class).exists()){
            elasticsearchRestTemplate.indexOps(Book.class).create();
            Document mapping = elasticsearchRestTemplate.indexOps(Book.class).createMapping();
            elasticsearchRestTemplate.indexOps(Book.class).putMapping(mapping);
            log.info("es库创建成功");
        }
    }

    @Scheduled(fixedRate = 1000*60)
    public void addes(){
        if (first){
            List<Book> books = bookdao.selectList(null);
            books.forEach( book -> {
                book.setBookEsflag(1);
                bookdao.updateById(book);
                elasticsearchRestTemplate.save(book);
            });
            log.info("第一次使用全量同步");
            first=false;
            return;
        }

        //定时增量同步
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Book::getBookEsflag,0);
        List<Book> books = bookdao.selectList(wrapper);
        books.forEach( book -> {
            book.setBookEsflag(1);
            bookdao.updateById(book);
            elasticsearchRestTemplate.save(book);
        });
        log.info("定时增量同步");
    }

}
